#include <string.h>
#include <ctype.h>
#include "str_utils.h"

int8_t is_delimeter(int ch)
{
    switch (ch)
    {
    case '\n': return SPACE_DELIMETER;
    case EOF: return SPACE_DELIMETER;
    case ' ': return SPACE_DELIMETER;
    case '>': return OUTCOMING_DELIMETER;
    case '<': return INCOMING_DELIMETER;
    case '|': return UNKNOWN_DELIMETER;
    case '&': return UNKNOWN_DELIMETER;
    default: return NO_DELIMETER;
    }
}

int8_t is_change_stream(char *expr)
{
    return (strncmp(expr, ">>", sizeof(char) * 2) == 0)
            || (strncmp(expr, ">", sizeof(char)) == 0)
            || (strncmp(expr, "<", sizeof(char)) == 0)
            || (strncmp(expr, "&>", sizeof(char) * 2) == 0)
            || (strncmp(expr, "&>>", sizeof(char) * 3) == 0);
}

int8_t get_run_chk_cond(char *expr)
{
      if (strncmp(expr, "&", sizeof(char)) == 0)
          return FOREGROUND_CONDITION;
      if (strncmp(expr, "&&", sizeof(char) * 2) == 0)
          return AND_CONDITION;
      if (strncmp(expr, "|", sizeof(char)) == 0)
            return PIPELINE_CONDITION;
      if (strncmp(expr, "||", sizeof(char) * 2) == 0)
          return OR_CONDITION;
      return NO_CONDITION;
}

int8_t check_delimeters(char *expr)
{
    int incoming_count = 0, outcoming_count = 0;
    int err_sep_count = 0, pipel_sep_count = 0;
    for (unsigned i = 0; i < strlen(expr); i++)
    {
        switch (expr[i])
        {
        case '>': outcoming_count++; break;
        case '<': incoming_count++; break;
        case '|': pipel_sep_count++; break;
        case '&': err_sep_count++; break;
        }
    }
    return (incoming_count < 2 && outcoming_count < 3 &&
            err_sep_count < 3  && pipel_sep_count < 3);
}

int8_t is_emptystr(char *expr)
{
    if (expr == NULL)
        return 1;
    int i = 0, e_len = strlen(expr);
    while (i < e_len && isspace(expr[i])) i++;
    return (i == e_len);
}

#ifdef POSIX_ONLY
char *strdup(char *expr)
{
    size_t expr_len = strlen(expr);
    char *res = xcalloc(expr_len + sizeof(char));
    strncpy(res, expr, expr_len);
    return res;
}
#endif

